<?php
/**
 * Created by PhpStorm.
 * User: priestll
 * Date: 20-7-15
 * Time: 上午8:59
 */

namespace App\Biz;


use App\Model\StageLogModel;
use App\Model\StageModel;
use App\Model\StageUserModel;
use EasySwoole\ORM\DbManager;
use priestll\easyswoole\biz\BaseBiz;

class StageBiz extends BaseBiz
{

    /**
     * 活动阶段数据
     */
    public function getStage()
    {
        $model = StageModel::create();
        $data = $model->getAll();
        return $this->success($data);
    }

    /**
     * @param $user_id
     * @return array
     */
    public function getUserStage($user_id)
    {
        $model = StageUserModel::create();
        $data = $model->getByUser($user_id);
        return $this->success($data);
    }

    /**
     * @param $user_id
     * @param $assist_id
     * @return array
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function assist($user_id, $assist_id)
    {
        $power = 5;
        $stageModel = StageModel::create();
        $stageUserModel = StageUserModel::create();
        $stageLogModel = StageLogModel::create();
        $log = $stageLogModel->get([
            'user_id' => $user_id,
            'assist_id' => $assist_id,
        ]);
        if ($log) {
            //return $this->success('已助力成功');
        }
        $userStage = $stageUserModel->getByWhere(['id' => $assist_id]);
        if (!$userStage) {
            return $this->fail('没有该数据');
        }
        $now = time();
        $stage = $userStage->stage();
        if ($now < $stage->beg_time || $now > $stage->end_time) {
            return $this->fail('不在活动期间');
        }
        $userStage->power += $power;
        if ($userStage->power >= $stage->power) {
            $nextStage = $stageModel->get($userStage->stage_id + 1);
            if ($nextStage) {
                $userStage->stage_id++;
            }
        }
        $db = DbManager::getInstance();
        try {
            //开启事务
            $db->startTransaction();

            $stageLogModel
                ->data([
                    'user_id' => $user_id,
                    'assist_id' => $assist_id,
                    'power' => $power,
                    'created_at' => time(),
                ])
                ->save();

            $userStage->update();

        } catch (\Throwable  $e) {
            //回滚事务
            $db->rollback();

            return $this->success($e->getMessage());
        } finally {
            //提交事务
            $db->commit();
            return $this->success('助力成功');
        }


    }


}